package cmd

import (
	"context"
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/louloulin/dataflare/pkg/workflow"
)

// RunWorkflow runs a workflow from a file
func RunWorkflow(filePath string, engineType string) error {
	// Parse workflow definition
	definition, err := workflow.ParseFromFile(filePath)
	if err != nil {
		return fmt.Errorf("failed to parse workflow: %w", err)
	}

	fmt.Printf("Running workflow: %s\n", definition.Name)

	// Create engine
	var engine *workflow.Engine
	switch engineType {
	case "actor":
		engine, err = workflow.NewEngine()
		if err != nil {
			return fmt.Errorf("failed to create engine: %w", err)
		}
		defer engine.Shutdown()
	default:
		return fmt.Errorf("unknown engine type: %s", engineType)
	}

	// Deploy workflow
	ctx := context.Background()
	fmt.Println("Deploying workflow...")
	workflowID, err := engine.DeployWorkflow(ctx, definition)
	if err != nil {
		return fmt.Errorf("failed to deploy workflow: %w", err)
	}
	fmt.Printf("Workflow deployed with ID: %s\n", workflowID)

	// Start workflow
	fmt.Println("Starting workflow...")
	runID, err := engine.StartWorkflow(ctx, workflowID, nil)
	if err != nil {
		return fmt.Errorf("failed to start workflow: %w", err)
	}
	fmt.Printf("Workflow started with run ID: %s\n", runID)

	// Wait for workflow to complete or for user to interrupt
	fmt.Println("Workflow is running. Press Ctrl+C to stop...")
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)

	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			// Get workflow status
			status, err := engine.GetWorkflowStatus(ctx, runID)
			if err != nil {
				fmt.Printf("Failed to get workflow status: %v\n", err)
				continue
			}

			fmt.Printf("Workflow status: %s (Progress: %d%%)\n", status.Status, status.Progress)

			if status.Status == "completed" || status.Status == "failed" {
				fmt.Printf("Workflow %s\n", status.Status)
				return nil
			}

		case <-sigCh:
			fmt.Println("Stopping workflow...")
			err := engine.StopWorkflow(ctx, runID)
			if err != nil {
				return fmt.Errorf("failed to stop workflow: %v", err)
			}

			fmt.Println("Workflow stopped successfully")
			return nil
		}
	}
}
